package com.reservoir.auth.service;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.reservoir.api.entity.ReUser;
import com.reservoir.api.model.LoginUser;
import com.reservoir.auth.dao.AuthMapper;
import com.reservoir.auth.form.AuthBody;
import com.reservoir.core.constant.CacheConstants;
import com.reservoir.core.constant.Constants;
import com.reservoir.core.constant.SecurityConstants;
import com.reservoir.core.constant.UserConstants;
import com.reservoir.core.entity.RestMsg;
import com.reservoir.core.exception.user.UserException;
import com.reservoir.core.exception.user.UserNoExitException;
import com.reservoir.core.exception.user.UserPasswordNotMatchException;
import com.reservoir.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author STARS
 * @edit HongZe
 * @create 2021-11-02
 */
@Service
public class AuthService {
    @Autowired
    private AuthMapper authMapper;
    @Autowired
    private RedisService redisService;
/**

 *@描述 token的过期时间
 *@问题 前端和后端的过期时间是否相同

 */
    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    /**

     *@描述 生成token与储存登陆用户信息

     */
    public Map<String, Object> createToken(ReUser loginUser)
    {
        // 使用生成token
        String token = JWT.create().withHeader(SecurityConstants.getHEADER())
            .withClaim(SecurityConstants.DETAILS_USER_ID,loginUser.getUserId())
            .withClaim(SecurityConstants.DETAILS_USERNAME,loginUser.getNickName())
            .sign(Algorithm.HMAC256(SecurityConstants.SECRET));

//        封装存在redis中的对象
        LoginUser User = new LoginUser();
        User.setToken(token);
        User.setUserid(loginUser.getUserId());
        User.setUsername(loginUser.getName());

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }

    /**

     *@描述 根据用户名和密码查询用户信息

     */
    public RestMsg<Object> login(AuthBody authBody) {
        ReUser user = new ReUser();
        AuthBody test = authMapper.selectByNickName(authBody);
        if (test == null) {
            throw new UserNoExitException();
        }
        if (test.getUserStatus().equals(UserConstants.USER_DISABLE) ) {
            throw new RuntimeException("账户已锁定");
        }
        if (!test.getPassword().equals(authBody.getPassword())) {
            throw new UserPasswordNotMatchException();
        }
        authMapper.updateLoginDateByUserId(test.getUserId());
        return RestMsg.ok(createToken(user));

    }


    public void refresh(String token) {
        redisService.expire(token,EXPIRE_TIME);
    }


    public RestMsg<Object> logout(String token) {
        redisService.del(token);
        return RestMsg.ok("账号已登出");
    }
}
